package com.csist.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csist.pojo.Admin;
import com.csist.service.impl.AdminServiceImpl;
import com.csist.utils.JwtUtil;
import com.csist.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Api
 */
@RestController
public class Api {
    @Autowired
    AdminServiceImpl adminService;
    @Value("${myConfig.imgPath}")
    private String imgPath;

    /**
     * login method
     * @param username
     * @param password
     * @return Return user on success
     */
    @RequestMapping("/login")
    public Admin login(String username, String password){
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("a_username",username);
        wrapper.eq("a_password",password);
        Admin user = adminService.getOne(wrapper);
        if (user!=null){
            user.setToken(JwtUtil.createToken());
        }
        return user;
    }

    /**
     * 验证token
     * @param request
     * @return true:验证成功,false:验证失败
     */
    @RequestMapping("/checkToken")
    public Boolean getUserSession(HttpServletRequest request){
        String token = request.getHeader("token");
        return JwtUtil.checkToken(token);
    }


    /**
     *  文件删除
     * @param filePath
     * @return
     */
    @RequestMapping("/removeFile")
    public boolean remove(String filePath){
        if (filePath==null) {
            return false;
        }
        File file = new File(filePath);
        return file.delete();
    }

    /**
     * 文章图片上传
     * @param file 文件
     * @return "filed":上传失败,上传完成后的文件绝对地址:上传成功
     */
    @RequestMapping("/imgUpload")
    public String eventsCoverUpload(@RequestParam("image") MultipartFile file){
        return Upload.upload(file,imgPath);
    }
}
